package com.neusoft.bizcore.activiti.converter;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.neusoft.bizcore.activiti.dto.PendingDataDTO;
import com.neusoft.bizcore.activiti.dto.ServiceDataModelDTO;
import com.neusoft.bizcore.activiti.model.PendingData;
import com.neusoft.bizcore.activiti.repository.PendingDataRepository;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.bizcore.web.utils.SpringUtil;

@Component
public class PendingDataConverter extends AbstractConverter<PendingData, PendingDataDTO> {

    @Autowired
    private PendingDataRepository pendingDataRepository;

    @Override
    public PendingData toModel(final PendingDataDTO dto) {

        PendingData model;

        if (dto.isNew()) {
            model = new PendingData();
            model.setCreateTime(new Date());
        } else {
            model = this.pendingDataRepository.getOne(dto.getId());
            model.setUpdateTime(new Date());
        }

        model.setContent(JSON.toJSONString(dto.getData()));

        if (StringUtils.isNotEmpty(dto.getWorkNum())) {
            final String instanceId =
                    SpringUtil.getBean(WorkOrderService.class).getInstanceIdByWorkorderNum(dto.getWorkNum());
            model.setInstanceId(instanceId);
        }
        if (StringUtils.isNotEmpty(dto.getTaskId())) {
            final String nodeId = SpringUtil.getBean(ProcessInstanceService.class).getNodeIdByTaskId(dto.getTaskId());
            model.setNodeId(nodeId);
        }
        model.setTaskId(dto.getTaskId());
        model.setWorkNum(dto.getWorkNum());
        model.setClazzName(dto.getClazzName());
        model.setMethodName(dto.getMethodName());
        model.setStatus(dto.getStatus());
        model.setName(dto.getName());
        model.setRemarks(dto.getRemarks());
        return model;
    }

    @Override
    public PendingDataDTO toDTO(final PendingData model, final boolean forListView) {

        final PendingDataDTO dto = new PendingDataDTO();

        dto.setId(model.getId());
        dto.setData(JSON.parseArray(model.getContent(), ServiceDataModelDTO.class));
        dto.setClazzName(model.getClazzName());
        dto.setTaskId(model.getTaskId());
        dto.setWorkNum(model.getWorkNum());
        dto.setMethodName(model.getMethodName());
        dto.setStatus(model.getStatus());

        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());

        dto.setName(model.getName());
        dto.setRemarks(model.getRemarks());
        return dto;
    }

}
